<?php
require_once "Image.php";
require_once "ImageForm.php";
require_once "App/MetadataService.php";

class App_ImageService
{
	protected $db;
	protected $image;
	protected $metadataService;
	
	function __construct()
	{
		$options = array(
			'host' => 'localhost',
			'username' => 'root',
			'password' => '',
			'dbname' => 'xpic'
		);
		
		$this->db = Zend_Db::factory('PDO_MYSQL', $options);
		Zend_Db_Table_Abstract::setDefaultAdapter($this->db);
		$this->image = new Image();
		$this->metadataService = new App_MetadataService();
		$this->session = new Zend_Session_Namespace('default');
		
		//$this->form = new App_Forms_ImageForm();
	}
	
	public function NewTestImage()
	{
		date_default_timezone_set('America/New_York');
		
		$params = array(
			'AlbumID' => $this->session->userID,
			'Name' => 'image_name',
			'Description' => 'image_desc',
			'CreatedDate' => date('Y-m-d G:i:s'),
			'ModifiedDate' => date('Y-m-d G:i:s')
		);
		
		$this->image->insert($params);
		
	}
	
	public function getPicsByAttr($name, $value)
	{
		$select = $this->image->select();
		$select->setIntegrityCheck(false);
		$select->from('image')
				->join('metadata', 'image.ImageID = metadata.ImageID');
				
		$select->where('metadata.Name = ?', $name);
		$select->where('metadata.Value = ?', $value);
		//$select->where('metadata.Name = ? and metadata.Value = ?', $name, $value);
		return $this->image->fetchAll($select);
	}
	
	public function getPicsByAttributes($names, $values)
	{
		$numElements = count($names);
		
		$select = $this->image->select();
		$select->setIntegrityCheck(false);
		$select->from('image')
			->join('metadata', 'image.ImageID = metadata.ImageID');

		$select->where('metadata.Name Like ?','%' . $names[0] . '%');
		$select->where('metadata.Value Like ?','%' . $values[0]. '%');
		for ($i = 1; $i < $numElements; $i++)
		{
			$select->orWhere('metadata.Name Like ?','%' . $names[$i] . '%');
			$select->where('metadata.Value Like ?','%' . $values[$i] . '%');
		}
		
		return $this->image->fetchAll($select);
	}
	
	public function getPicsFromAlbumByID($albumID) 
	{
		$select = $this->image->select();
		$select->where('AlbumID=?', $albumID);
		return $this->image->fetchAll($select);	
	}
	
	public function saveImage($albumID, $filePath, $name="", $desc="")
	{
		$params = array(
			'AlbumID' => $albumID,
			'Filepath' => $filePath,
			'Name' => $name,
			'Description' => $desc,
			'CreatedDate' => date('Y-m-d G:i:s'),
			'ModifiedDate' => date('Y-m-d G:i:s')
		);
		
		$imageID = $this->image->insert($params);
		$this->metadataService->updateMetadata($imageID, 'Name', basename($filePath));
		$this->metadataService->updateMetadata($imageID, 'User', $this->session->userName);
		$this->metadataService->updateMetadata($imageID, 'Created Date', date('Y-m-d G:i:s'));
		$this->metadataService->updateMetadata($imageID, 'Modified Date', date('Y-m-d G:i:s'));
	}
}